/*
 * Copyright (c) Created by T C L on 2019.7.6.
 */

package cn.mumzone.pos.ui.dialog;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.model.CardReturnEntity;
import cn.mumzone.pos.model.ReturnEntity;
import cn.mumzone.pos.model.SunMiPayResponse;
import cn.mumzone.pos.model.TimeCardEntity;
import cn.mumzone.pos.presenter.TimesCardReturnPresenter;
import cn.mumzone.pos.presenter.contract.TimesCardReturnContract;
import cn.mumzone.pos.ui.activity.ACT_UpReturnMoneyAuth;

public class TimesCardReturnDialogFragment extends DialogFragment implements TimesCardReturnContract.View {

    private static final int REQUEST_CODE = 101;

    @BindView(R.id.tv_card_name)
    TextView tvCardName;
    @BindView(R.id.tv_card_des)
    TextView tvCardDes;
    @BindView(R.id.tv_card_use_info)
    TextView tvCardUseInfo;
    @BindView(R.id.tv_card_last_time)
    TextView tvCardLastTime;
    @BindView(R.id.tv_card_price)
    TextView tvCardPrice;
    @BindView(R.id.tv_card_info)
    TextView tvCardInfo;
    @BindView(R.id.tv_card_expiry_date)
    TextView tvCardExpiryDate;
    @BindView(R.id.tv_card_count)
    TextView tvCardCount;
    @BindView(R.id.tv_card_use_count)
    TextView tvCardUseCount;
    @BindView(R.id.tv_card_last_count)
    TextView tvCardLastCount;
    @BindView(R.id.tv_return_amount)
    TextView tvReturnAmount;

    @BindView(R.id.tv_real_return_amount)
    TextView tvRealReturnAmount;

    @BindView(R.id.lb_return_card)
    LoadingButton lbReturnCard;

    private TimeCardEntity timeCardEntity;
    private CardReturnEntity cardReturnEntity;
    private TimesCardReturnPresenter presenter;

    private String memberPhone;

    private FragmentActivity activity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (FragmentActivity) activity;
    }

    @Override
    public void onStart() {
        super.onStart();
        getDialog().setCanceledOnTouchOutside(false);//点击外部不消失
        // 设置SelectPicPopupWindow弹出窗体的背景
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        window.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
        params.gravity = Gravity.CENTER;
        params.width = DisplayUtil.dip2px(activity, 386);
        params.height = DisplayUtil.dip2px(activity, 648);
        window.setAttributes(params);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        memberPhone = getArguments().getString("memberPhone");
        timeCardEntity = (TimeCardEntity) getArguments().getSerializable("timeCardEntity");
        presenter = new TimesCardReturnPresenter(activity, this);
        presenter.initEvent();

    }



    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_times_card_return, container, false);
        ButterKnife.bind(this, view);
        tvCardName.setText(StringUtils.get(timeCardEntity.getGoodsName()));
        tvCardDes.setText(StringUtils.get(timeCardEntity.getServiceName()));
        tvCardUseInfo.setText(String.format("%s/%s次",
                StringUtils.get(timeCardEntity.getResidueTimes()),
                StringUtils.get(timeCardEntity.getTimes())));
        tvCardLastTime.setText(String.format("有效期至：%s",
                AppDateUtil.getTimeStamp(timeCardEntity.getEndDate(), AppDateUtil.YYYY_MM_DD2)));

        tvCardPrice.setText("￥" + timeCardEntity.getTicketPrice());
        tvCardInfo.setText(timeCardEntity.getServiceName());
        tvCardExpiryDate.setText(AppDateUtil.getTimeStamp(timeCardEntity.getEndDate(), AppDateUtil.YYYY_MM_DD2));
        tvCardCount.setText(String.valueOf(timeCardEntity.getTimes()));
        tvCardUseCount.setText(String.valueOf(timeCardEntity.getTimes() - timeCardEntity.getResidueTimes()));
        tvCardLastCount.setText(String.valueOf(timeCardEntity.getResidueTimes()));

        presenter.requestReturnCardDetail(timeCardEntity.getId(), String.valueOf(timeCardEntity.getTimes()),
                String.valueOf(timeCardEntity.getResidueTimes()), timeCardEntity.getGoodsId(),
                timeCardEntity.getOrderCode());
        return view;
    }

    @Override
    public void setReturnCardDetailData(CardReturnEntity cardReturnEntity) {
        this.cardReturnEntity = cardReturnEntity;
        tvCardPrice.setText("￥" + cardReturnEntity.getPrice());
        tvReturnAmount.setText("￥" + cardReturnEntity.getResiduePrice());
        tvRealReturnAmount.setText("￥" + cardReturnEntity.getResiduePrice());
    }

    @Override
    public void onReturnSuccess(List<ReturnEntity> returnEntities) {
        lbReturnCard.stopLoading("退卡");
        TimesCardReturnSuccessDialogFragment timesCardReturnSuccessDialogFragment =
                new TimesCardReturnSuccessDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("cardId", timeCardEntity.getId());
        bundle.putSerializable("money", (Serializable) returnEntities);
        bundle.putString("memberPhone", memberPhone);
        bundle.putSerializable("timeCardEntity", timeCardEntity);
        timesCardReturnSuccessDialogFragment.setArguments(bundle);
        timesCardReturnSuccessDialogFragment.show(activity.getSupportFragmentManager(),
                "timesCardReturnSuccess");
        dismiss();
    }

    @Override
    public void onReturnFailed(String errorMsg) {
        lbReturnCard.stopLoading("退卡");
        TimesCardReturnFailedDialogFragment timesCardReturnFailedDialogFragment =
                new TimesCardReturnFailedDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("cardId", cardReturnEntity.getId());
        bundle.putString("memberPhone", memberPhone);
        bundle.putString("price", tvRealReturnAmount.getText().toString().replace("￥", ""));
        bundle.putString("residuePrice", tvReturnAmount.getText().toString().replace("￥", ""));
        bundle.putString("goodsId", cardReturnEntity.getGoodsId());
        bundle.putString("orderCode", cardReturnEntity.getOrderCode());
        bundle.putSerializable("timeCardEntity", timeCardEntity);
        bundle.putSerializable("errorMsg", errorMsg);
        bundle.putString("returnMargin",
                String.valueOf(Double.parseDouble(cardReturnEntity.getResiduePrice()) - Double.parseDouble(tvReturnAmount.getText().toString().replace("￥", ""))));
        timesCardReturnFailedDialogFragment.setArguments(bundle);
        timesCardReturnFailedDialogFragment.show(activity.getSupportFragmentManager(),
                "timesCardReturnFailed");
        dismiss();
    }

    @Override
    public void setRealReturnMoney(String realMoney) {
        tvRealReturnAmount.setText("￥" + realMoney);
    }

    @Override
    public void showUpdateReturnAmount() {
        TimesCardReturnMoneyInputDialogFragment timesCardReturnMoneyInputDialogFragment =
                new TimesCardReturnMoneyInputDialogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("money", cardReturnEntity.getPrice());
        timesCardReturnMoneyInputDialogFragment.setArguments(bundle);
        timesCardReturnMoneyInputDialogFragment.show(activity.getSupportFragmentManager(),
                "timesCardReturnMoneyInput");
    }

    @Override
    public void goAuthView() {
        ACT_UpReturnMoneyAuth.startAcForResult(activity, REQUEST_CODE);
    }


    @OnClick(value = {R.id.iv_close, R.id.iv_update_amount, R.id.lb_return_card})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.iv_update_amount:
                if (cardReturnEntity == null) {
                    return;
                }
                presenter.verifyReturnAuth();
                break;
            case R.id.lb_return_card:
                if (cardReturnEntity == null) {
                    return;
                }
                lbReturnCard.startLoading("正在退卡");
                presenter.goReturnCard(cardReturnEntity.getId(), cardReturnEntity.getPrice(),
                        tvRealReturnAmount.getText().toString().replace("￥", ""), cardReturnEntity.getGoodsId(),
                        cardReturnEntity.getOrderCode(),
                        String.valueOf(Double.parseDouble(cardReturnEntity.getResiduePrice()) - Double.parseDouble(tvReturnAmount.getText().toString().replace("￥", ""))));
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            showUpdateReturnAmount();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.destroy();
    }

}
